package client.comm.commlib.base

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import androidx.paging.LoadState
import androidx.paging.LoadStateAdapter
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import client.comm.commlib.R
import client.comm.commlib.databinding.LayoutRcPagingloadmoreBinding

class PagerFooterAdapter() :
    LoadStateAdapter<PagingViewHoder>() {

    override fun onBindViewHolder(holder: PagingViewHoder, loadState: LoadState) {
        val binding = holder.binding as LayoutRcPagingloadmoreBinding
        binding.loading.isVisible = loadState is LoadState.Loading


        if (loadState.endOfPaginationReached) { //加载完成
            binding.message.text = "没有更多数据了"
        } else {
            binding.root.visibility = View.VISIBLE
            binding.message.text = if (loadState is LoadState.Error) "网络错误" else "加载中..."
        }

    }

    override fun onViewAttachedToWindow(holder: PagingViewHoder) {
        super.onViewAttachedToWindow(holder)
        val lp: ViewGroup.LayoutParams = holder.itemView.getLayoutParams()
        if (lp != null && lp is StaggeredGridLayoutManager.LayoutParams
        ) {
            lp.isFullSpan = true
        }
    }

    override fun displayLoadStateAsItem(loadState: LoadState): Boolean {
//        if (loadState is LoadState.Error || loadState is LoadState.Loading) {
//            return super.displayLoadStateAsItem(loadState)
//        }
//        return loadState.endOfPaginationReached
        return super.displayLoadStateAsItem(loadState) || (loadState is LoadState.NotLoading && loadState.endOfPaginationReached)
    }

    override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState): PagingViewHoder {
        return PagingViewHoder(
            DataBindingUtil.inflate(
                LayoutInflater.from(parent.context),
                R.layout.layout_rc_pagingloadmore,
                parent,
                false
            )
        )
    }

}